|
|
|
|
|
|
|
easy thing to miss. A memory leak is caused when some part of your program allocates memory but fails to release it. Where is the memory leak in this case? |
|
|
|
|
|
|
|
|
Look again at Figure S27-2. The StringFromCLSID function loads the MemoryPointer variable that you passed as a parameter with a pointer to the string containing a representation of the CLSID parameter. That string occupies data in memory. Where does the data come from? |
|
|
|
|
|
|
|
|
The StringFromCLSID function allocates it! |
|
|
|
|
|
|
|
|
Take another look at the description of the parameters: |
|
|
|
|
|
|
|
|
rclsid
[in] CLSID to be converted.
ppsz
[out] Pointer to the resulting string. |
|
|
|
|
|
|
|
|
What do the prefixes [in] and [out] mean? Remember that you are now dealing with the OLE subsystema part of the Win32 API that works differently in some ways from the regular Win32 API functions. You already saw in the previous puzzle that error handling in the OLE subsystem is different from that in normal Win32 API functions. It turns out that parameters work by different rules as well. Every parameter is defined as being an [in] parameter, an [out] parameter, or an [in-out] parameter. |
|
|
|
 |
|
 |
|
|
[in] parameters are allocated and freed by the caller.
[out] parameters are allocated by the API function and must be freed by the caller using the OLE memory allocator.
[in-out] parameters are allocated by the caller and may be freed and reallocated by the API function. The caller is ultimately responsible for freeing the parameter. |
|
|
|
|
|
|
|
|
In each case, you'll need to refer to the function documentation to determine how to allocate or free the memory in question. OLE actually uses several distinct memory allocation systems depending on the subsystem in use. |
|
|
|
|
|
|
|
|
In this case, the string whose pointer is loaded into the MemoryPointer variable is allocated by the API function. It is your responsibility to free the buffer when it is no longer needed. Fortunately, this is very easy to accomplish. |
|
|
|
|
|
|
|
|
The CoTaskMemFree API function allows you to free memory that is allocated by the OLE memory allocator. It is declared in Visual Basic as follows: |
|
|
|
|
|
|
|
|
Private Declare Sub CoTaskMemFree Lib "ole32.dll" (ByVal ptr As Long) |
|
|
|
|
|